﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GodSystem
{
    public partial class FormUpdate : Form
    {
        BackgroundWorker worker = new BackgroundWorker();
        public FormUpdate()
        {
            InitializeComponent();
            worker.WorkerReportsProgress = true;
            worker.WorkerSupportsCancellation = true;

            worker.RunWorkerCompleted += CompleteWork;
            worker.ProgressChanged += UpdateProgressBar;
        }

        private void UpdateProgressBar(object sender, ProgressChangedEventArgs e)
        {
            if (this.progressBar1.Maximum >= e.ProgressPercentage)
            {
                this.progressBar1.Value = e.ProgressPercentage;
            }
            this.label2.Text = ((int)((e.ProgressPercentage * 100) / this.progressBar1.Maximum)).ToString() + "%";
        }

        private void CompleteWork(object sender, RunWorkerCompletedEventArgs e)
        {
            DialogResult = DialogResult.OK;
        }
        protected override void OnClosing(CancelEventArgs e)
        {
            if (worker != null && worker.IsBusy)
            {
                worker.CancelAsync();
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            if (worker != null && worker.IsBusy)
            {
                worker.CancelAsync();
            }
            else
            {
                this.DialogResult = DialogResult.Cancel;
            }
        }

        private void DoThing(object sender, DoWorkEventArgs e)
        {
            try
            {
                string downUrl = "http://local.test.com/csharp/Update2022Release.zip";
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(downUrl);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                long totalBytes = response.ContentLength;
                BeginInvoke(new Action(() => { progressBar1.Maximum = (int)totalBytes; }));


                string filename = "newFile.zip";
                Stream st = response.GetResponseStream();
                Stream so = new FileStream(filename, FileMode.Create);
                long totalDownloadedByte = 0;
                byte[] by = new byte[1024 * 5];
                int osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = totalDownloadedByte + osize;
                    so.Write(by, 0, osize);
                    worker.ReportProgress((int)totalDownloadedByte);
                    osize = st.Read(by, 0, (int)by.Length);
                    Thread.Sleep(100);
                    if (worker.CancellationPending)
                    {
                        so.Close();
                        st.Close();
                        break;
                    }
                }
                so.Close();
                st.Close();

                if (Unzip(filename, "newFile"))
                {
                    File.Delete(filename);
                    Cmd("reboot.bat");
                    Process.GetCurrentProcess().Kill();
                }
                else
                {
                    MessageBox.Show("解压失败!");
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private bool Unzip(string fileToUnzip, string zipedFold)
        {
            bool flag = true;
            try
            {
                if (Directory.Exists(zipedFold))
                {
                    Directory.Delete(zipedFold, true);
                }
                System.IO.Compression.ZipFile.ExtractToDirectory(fileToUnzip, zipedFold);
            }
            catch(Exception ex)
            {
                MessageBox.Show("解压出现异常：" + ex.Message);
                flag = false;
            }

            return flag;
        }

        private void Cmd(string bat)
        {
            Process proc = new Process();
            proc.StartInfo.FileName = bat;
            proc.StartInfo.WorkingDirectory = Application.StartupPath;
            proc.StartInfo.UseShellExecute = true;
            proc.StartInfo.RedirectStandardOutput = false;
            proc.StartInfo.RedirectStandardInput = false;
            proc.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
            proc.StartInfo.CreateNoWindow = false;
            proc.Start();
            proc.Close();
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            worker.DoWork += DoThing;
            if (!worker.IsBusy)
            {
                label2.Text = "正在下载文件中....";
                worker.RunWorkerAsync();
            }
        }
    }
}
